<template>
  <div class="add-salesman">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title">
          <i class="el-icon-plus"></i>
          添加业务员
        </span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="resetForm">重置表单</el-button>
      </div>

      <el-form
        :model="salesmanForm"
        :rules="salesmanRules"
        ref="salesmanForm"
        label-width="120px"
        class="salesman-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务员姓名" prop="name">
              <el-input
                v-model="salesmanForm.name"
                placeholder="请输入业务员姓名"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="salesmanForm.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNo">
              <el-input
                v-model="salesmanForm.idNo"
                placeholder="请输入身份证号"
                maxlength="18"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input
                v-model="salesmanForm.email"
                placeholder="请输入邮箱地址"
                type="email"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属区域" prop="regionId">
              <el-select
                v-model="salesmanForm.regionId"
                placeholder="请选择所属区域"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="region in regionList"
                  :key="region.id"
                  :label="region.name"
                  :value="region.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 预留位置，保持布局平衡 -->
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="详细地址/备注" prop="address">
              <el-input
                v-model="salesmanForm.address"
                type="textarea"
                :rows="3"
                placeholder="请输入详细地址/备注（可选）"
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 业务员编号说明 -->
        <el-alert
          title="业务员编号说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template slot="default">
            <p>总部添加的业务员将直接创建，无需审核</p>
            <p>业务员编号将在创建后自动生成，格式为8位数字（如：00000001）</p>
            <p>请确保填写的信息准确无误，系统将自动创建业务员账号</p>
          </template>
        </el-alert>

        <el-form-item style="margin-top: 20px;">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            <i class="el-icon-check"></i>
            添加业务员
          </el-button>
          <el-button @click="resetForm">
            <i class="el-icon-refresh-left"></i>
            重置表单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 提交成功提示 -->
    <el-dialog
      title="提交成功"
      :visible.sync="successDialogVisible"
      width="450px"
      :close-on-click-modal="false"
      custom-class="view-dialog">
      <div class="success-content">
        <i class="el-icon-success success-icon"></i>
        <h3>业务员添加成功！</h3>
        <p>业务员已成功创建，无需审核，可直进入业务员管理页面查看</p>
        <div class="success-info">
          <p><strong>姓名：</strong>{{ salesmanForm.name }}</p>
          <p><strong>手机：</strong>{{ salesmanForm.phone }}</p>
          <p><strong>身份证：</strong>{{ maskIdNo(salesmanForm.idNo) }}</p>
          <p><strong>状态：</strong>已创建</p>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSuccessConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSalesman, getRegionList } from '@/api/aggregation'

export default {
  name: 'AddSalesman',
  data() {
    return {
      submitLoading: false,
      successDialogVisible: false,

      // 业务员表单数据
      salesmanForm: {
        name: '',
        phone: '',
        idNo: '',
        email: '',
        regionId: null,
        address: ''
      },

      // 表单验证规则
      salesmanRules: {
        name: [
          { required: true, message: '请输入业务员姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        idNo: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },

      // 区域列表
      regionList: []
    }
  },
  mounted() {
    this.loadRegionList()
  },
  methods: {
    // 加载区域列表
    async loadRegionList() {
      try {
        Logger.log('=== 加载区域列表 ===')
        const response = await getRegionList()
        Logger.log('区域列表API响应:', response)

        if (response.code === 0) {
          // 处理分页数据
          this.regionList = response.data?.list || response.data || []
        } else {
          Logger.warn('区域列表为空，将不显示区域选择')
          this.regionList = []
        }
      } catch (error) {
        Logger.error('加载区域列表失败:', error)
        Logger.warn('区域列表加载失败，将不显示区域选择')
        this.regionList = []
      }
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.salesmanForm.validate()
        this.submitLoading = true

        Logger.log('=== 总部直接添加业务员（无需审核） ===')
        Logger.log('表单数据:', this.salesmanForm)

        // 准备提交数据 - 总部添加业务员直接调用addSalesman接口，无需审核
        const submitData = {
          name: this.salesmanForm.name,
          phone: this.salesmanForm.phone,
          idNo: this.salesmanForm.idNo,
          email: this.salesmanForm.email || '',
          address: this.salesmanForm.address || '', // 将备注作为地址
          regionId: this.salesmanForm.regionId || null,
          password: '123456' // 默认密码，业务员后续可自行修改
        }

        const response = await addSalesman(submitData)
        Logger.log('添加业务员API响应:', response)

        if (response.code === 0) {
          this.successDialogVisible = true
          this.$message.success('业务员添加成功，已直接创建账号')
        } else {
          this.$message.error(response.msg || response.data?.msg || '添加业务员失败')
        }
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          Logger.error('添加业务员失败:', error)
          this.$message.error('添加业务员失败: ' + (error.message || '未知错误'))
        }
      } finally {
        this.submitLoading = false
      }
    },

    // 重置表单
    resetForm() {
      this.$refs.salesmanForm.resetFields()
      this.salesmanForm = {
        name: '',
        phone: '',
        idNo: '',
        email: '',
        regionId: null,
        address: ''
      }
    },

    // 成功确认
    handleSuccessConfirm() {
      this.successDialogVisible = false
      this.resetForm()
    },

    // 遮罩身份证号
    maskIdNo(idNo) {
      if (!idNo) return '未填写'
      if (idNo.length < 10) return idNo
      return idNo.substring(0, 6) + '****' + idNo.substring(idNo.length - 4)
    }
  }
}
</script>

<style scoped>
.add-salesman {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.salesman-form {
  max-width: 800px;
  margin: 0 auto;
}

.salesman-form .el-form-item {
  margin-bottom: 20px;
}

/* 成功对话框样式 */
.success-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 20px;
  display: block;
}

.success-content h3 {
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 10px;
}

.success-content p {
  color: #6c757d;
  margin-bottom: 20px;
}

.success-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  text-align: left;
  margin-top: 20px;
}

.success-info p {
  margin: 8px 0;
  color: #495057;
}

/* 对话框底部样式已移至公共样式 dialog.scss */

/* 表单样式优化 */
.el-input, .el-select, .el-textarea {
  border-radius: 6px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

.el-button--primary {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 卡片头部样式 */
.el-card__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 8px 8px 0 0;
}

.el-card__header .clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
